<template>
	<view>
	<u-navbar back-text="" :leftIconColor="tksetting.titlecolor" :bgColor="tksetting.color" :titleStyle="{color:tksetting.titlecolor}" :title="title"  :autoBack="true"  :placeholder="true">
		
	</u-navbar>
	<view class="content">
		<!-- 轮播图区域 -->
		<swiper class="swiper" :style="{ height: swiperHeight + 'px' }" :duration="swiperDuration" :circular="true"
			:autoplay="swiperConfig.autoplay" :interval="swiperConfig.interval" :vertical="swiperVertical"
			:current="swiperCurrent" @change="swiperChange">
			<swiper-item class="swiper-item" v-for="(json, index) in swiperList" :key="index">
				<view class="page-item" v-if="json.index != null">
					<view class="menu">
						<view class="left">{{ json.index + 1 }} / {{ mount }}</view>
						<view class="right" style="display: flex;justify-content: flex-end;"  @click="cls_store">
							<u-icon name="reload"></u-icon> <text>重做</text>
						</view>
					</view>
					
					
					
					<view class="title-info">
						<text :class="'type type-' + json.classid">{{ getType(json.classid) }}</text>
						<rich-text :nodes="json.question"></rich-text>
					</view>
					<!-- 单选题和判断题 -->
					<radio-group v-if="json.classid == '1' ||  json.classid == '3'" class="options" @change="radioChange">
						<label class="option flex-box" v-for="(value, key) in json.daan"
							:class="{ checked: json.checked.includes(key)}" :key="key">
							<radio class="radio" style="margin-right:10rpx;display:none;" :disabled="json.disabled"
								:value="key" :checked="json.checked.includes(key)" />
							<view class="option-head">{{upPer(key)}}</view>
							<view v-if="ispic(value)" class="option-body">
									<u--image
									style="text-align: left;"
									:showLoading="true"
									radius="12"
									:src="value"
									mode="heightFix"
									height="120px"
								    ></u--image>
							</view>
							<view v-else  class="option-body">{{ value }}</view>
						</label>
					</radio-group>

					<!-- 多选题 -->
					<checkbox-group v-if="json.classid == '2'" class="options" @change="checkboxChange">
						<label class="option flex-box" v-for="(value, key) in json.daan" :class="{
								checked: json.checked.includes(key)
							}" :key="key">
							<checkbox class="checkbox" style="margin-right:10rpx;display:none;"
								:checked="json.checked.includes(key)" :disabled="json.disabled" :value="key"/>
							<view class="option-head">{{ upPer(key) }}</view>
							<view v-if="ispic(value)" class="option-body">
									<u--image
									style="text-align: left;"
									:showLoading="true"
									radius="12"
									:src="value"
									mode="heightFix"
									height="120px"
								    ></u--image>
							</view>
							<view v-else  class="option-body">{{ value }}</view>
						</label>
						<view :class="[
								'check-confirm',
								json.userAnswer.length > 1 && !json.finish ? 'hightlight' : ''
							]"  @click="checkConfirm">
							确定答案
						</view>
					</checkbox-group>
					
					<!-- 问答题 -->
					<view class="uni-textarea options" v-if="json.classid == '4' || json.classid == '5' ">
								<textarea style="background: #eaeaea; width: 100%; padding: 12rpx;"  @input="onInput" :value="json.userAnswer" :disabled="json.disabled" />
								<view :class="[
										'check-confirm',
										json.userAnswer.length > 1 && !json.finish ? 'hightlight' : ''
									]"  @click="checkConfirm_wd">
									确定答案
								</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		<!--<view class="page" v-if="!swiperConfig.autoplay">
			<view @click="lastPage">上一题</view>
			<view @click="nextPage">下一题</view>
		</view> -->
		<!-- 底部操作区域 -->
		
	</view>
	
	
	<view class="handle"  v-if="question && !swiperConfig.autoplay">
		<view class="item card" @click="qusCard = true">
			<u-icon name="grid"  ></u-icon>
			<view>答题卡</view>
		</view>
		<view class="item dayi" @click="submit_sj">
			<u-icon name="fingerprint"  ></u-icon>
			<view>提交</view>
		</view>
		<view class="item"  @click="note">
			<u-icon name="clock"  ></u-icon>
			<view>
				   <u-count-down
				            :time="1.5*60*60*1000"
				            format="HH:mm:ss"
				            autoStart
				            @change="timeonChange"
							@finish="time_out"
				    >
					<view>
						{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}:{{ timeData.minutes }}:{{ timeData.seconds }}
					</view>
				</u-count-down>
			</view>
		</view>
	</view>	
	<!-- 答题卡 弹出层 -->
	<view v-show="qusCard">
		<my-popup-card :top="top_num" :color="tksetting.color" :questions="questions" mode="1" @close="qusCard = false" @swiperTo="initSwiper($event)">
		</my-popup-card>
	</view>
		
	</view>
</template>

<script>

	import {toast,showModal,isImageUrlByExtension, clearStorageSync, setStorageSync, getStorageSync, useRouter} from '@/utils/utils.js'
	import swiper from '@/utils/swiper.js';
	import { mapState } from 'vuex';
	export default {
		data() {
			return {
				ks_time:1.5*60*60*1000,
				timeData:{hours:0,minutes:0,seconds:0},
				bijishow:false,
				swiperHeight: '',
				// mode 1：表示普通做题模式 0：表示背题模式
				mode: null,
				ksid:'',
				text: 'yt',
				keys:'',
				update:'',
				id: '',
				title: '',
				// 题目总数
				mount: '',
				// 用户是否能够购买
				have: '',
				// 题目列表
				questions: [],
				// 当前题目
				question: {},
				// 当前swiper渲染的items
				swiperList: [],
				// 滑动到的位置
				swiperIndex: 0,
				// 此值控制swiper的位置
				swiperCurrent: 0,
				// 值为0禁止切换动画
				swiperDuration: 250,
				// 需要几个swiperItem, 最少值为3,如果有分页的需求，可以是10、20, 任何
				swiperListLength: 4,
				// swiper 的个人设定
				swiperConfig: {
						tc:false,
						zdqh:false,
						fx:false,
						ytfx:false,
						interval:0,
						ksfx:false,
						audio:false,
						autoplay: false
					},
				lastIndex: 0,
				lastShow: false,
				// 是否显示错误提示
				mask: false,
				// 是否显示答题卡  微信  方便客服与你联系
				qusCard: false,
				daojishi:30 * 60 * 60 * 1000,
				time:0,
				audios:null,
				//测试数据
				headHeight:'',
				
			};
		},

		async onLoad(opt) {
			//console.log(opt);
			
			let shebei = this.shebei_info;
			
			this.swiperHeight = Number(shebei.screenHeight ?? 0) - Number(shebei.statusBarHeight ?? 0) - Number(shebei.screenTop ?? 0);
			this.headHeight=shebei.statusBarHeight;
			//const params = JSON.parse(decodeURIComponent(opt.data));
			this.id = 3;
			await this.init();
			uni.setNavigationBarTitle({
			      title: this.title
			});
			
		},
		onShareAppMessage(res) {
			
		},

		onShareTimeline() {
			
		},
		onReady() {},
		mounted(){
			
			this.setting.forEach(item => {
			  this.swiperConfig[item.name] = item.value;
			});
			
		},
		
		computed: {
			...mapState(['user','shebei_info','tksetting','setting']),
			swiperVertical() {
				return this.swiperConfig.fx;
			},
			storageKey() {
				return `wenjuan${this.id}`
				//return `zjlx${this.id+this.nickname}`
			},
			top_num(){
			       return this.headHeight+this.shebei_info.safeArea.top
			}
		},

		methods: {
			async init() {
				const that = this;
				await that.getData();
			},
			async cls_store(){
				let that=this;
				uni.showModal({
					title: '系统提示',
					content: '是否清理答题记录,清除后不能恢复?',
					success(res) {
						if (res.confirm) {
							let newArr = that.questions.map(obj => {
							  return {...obj, userAnswer: '',finish:false,show:false,checked:''}; // 创建对象的浅拷贝并将 'b' 键的值设为 undefined
							});
							that.questions=newArr;
							that.initSwiper(0);
							that._optChange();
							that.init();
						}
					}
				});
			},

			async getData() {
				let that = this;
				let data;
				data = await this.$api.kaoshi({id: this.id,text:this.text});
				
				if (data.code == 0) {
					
					this.have = data.have || false;
					this.keys=data.nickname;
					
					const localData = uni.getStorageSync(this.storageKey)
					if (!localData) {
						this.mount = data.row;
						this.nickname = data.nickname;
						this.title=data.title;
						// 初始化swiper配置项
						this.lastIndex = 0
						//this.time = data.sj.kssj || 90 * 60
						// 初始化问题列表
						let questions = data.data;
						for (let [item, index] of questions.map((item, index) => [item, index])) {
							item.index = index;
							this.setData(item);
							// this.setDataForTest(item);
						}
						this.questions = questions;
					} else {
						await that.setLocalData(localData);
					}
					
					await that.initSwiper(that.lastIndex);
					
				
				} else {
					uni.showModal({
						title: '系统提示',
						content: data.msg || '未查询到题目,请联系管理员',
						success(res) {
							uni.navigateBack()
						}
					});
				}
			},
			setLocalData(localData) {
				localData = JSON.parse(localData)
				for (let key in localData) {
					this[key] = localData[key]
				}
			},
			setData(obj) {
				let initObj = {
					show: false,
					userAnswer: '',
					isRight: '',
					disabled: false,
					finish: false,
					checked: ''
				};
				obj = Object.assign(obj, initObj);
			},
			// 初始化swiperlist
			initSwiper(lastIndex) {
				const that = this;
				that.swiperList = swiper.initSwiperList(that, lastIndex);
				
			},
			goLast() {
				this.initSwiper(this.lastIndex);
				//this.lastShow = false;
			},
			// 监听swiper改变
			swiperChange(e) {
				const that = this;
				let current = e.detail.current;
				const ti_end=swiper.changePage(that, current);
				if(ti_end=='end'){
					//this.lastPage();
					uni.showModal({
						title:'系统提示',
						content:'已经是最后一题了',
						showCancel:false,
						success(){
							that.initSwiper(that.lastIndex);
						}
					})
					
				}
				
				//that.lastShow = false
				
			},
			// 上一题
			lastPage() {
				this.swiperCurrent = this.swiperIndex > 0 ? this.swiperIndex - 1 : this.swiperListLength - 1;
			},
			// 下一题
			nextPage() {
				this.swiperCurrent = this.swiperIndex < this.swiperListLength - 1 ? this.swiperIndex + 1 : 0;
			},
			// 根据typeid判断题目类型
			getType(typeId) {
				let type = '';
				switch (typeId) {
					case '1':
						type = '单选题';
						break;
					case '2':
						type = '多选题';
						break;
					case '3':
						type = '判断题';
						break;
					case '4':
						type = '问答题';
						break;
					case '5':
					    type = '填空题';
					break;
				}
				return type;
			},
			upPer(str){
				if(str){
					return str.toUpperCase()
				}
			},
			// 通过代码选中正确答案，点击提示按钮时会用到此函数
			checkBy(answer) {
				this.question.checked = answer;
			},

			maskControll() {
				// 判断用户的答案与标准答案是否匹配
				let swiperConfig = this.swiperConfig;
				let question = this.question;
				this.nextPage();
			},
			async _optChange() {
				const that = this
				// 本地存储记录
				const record = {
					mount: this.mount,
					text: this.text,
					title:this.title,
					nickname:this.nickname,
					//swiperConfig: this.swiperConfig,
					questions: this.questions,
					time: this.time,
					lastIndex: this.question.index
				}
				// 提交数据
				this.question.finish = true;
				this.question.isRight = this.question.answer == this.question.userAnswer ? true : false;
				uni.setStorageSync(this.storageKey, JSON.stringify(record))
				//this.nextPage();
			},
			// 单选题选择
			async radioChange(e) {
				
				const that = this;
				const question = that.question;
				this.checkBy(e.detail.value);
				// 获取到当前选项的值
				this.question.userAnswer = e.detail.value;
				this.question.isRight = this.question.answer == e.detail.value ? true : false;
				if (this.question.dui == null) {
					this.question.dui = 0;
					this.question.cuo = 0;
				}
				this.question.isRight ? this.question.dui++ : this.question.cuo++;
				// 点击后禁用单选按钮
				//this.question.disabled = true;
				this.question.finish = true;
				this.question.show = true;
				this.maskControll();
				await this._optChange()
				this.$api.record({
							tid: question.id,
							zid: question.zid,
							text: that.text,
							type: that.question.isRight ? 1 : 2
				})
			},
			// 多选题选择
			checkboxChange(e) {
				let userAnswer = e.detail.value.sort().join('');
				this.question.userAnswer = userAnswer;
				// this.question.temp = userAnswer
				this.checkBy(userAnswer);
			},
			//填空题填写绑定
			onInput(e){
				let userAnswer = e.detail.value;
				this.question.userAnswer = userAnswer;
			}
			,
			// 确定多选题的选项
			checkConfirm() {
				
				const that = this;
				let question = this.question;
				if (this.question.userAnswer && this.question.userAnswer.length > 1) {
					this._optChange()
					//this.question.disabled = true;
					this.question.finish = true;
					this.question.show = true;
					this.question.isRight = this.question.answer == this.question.userAnswer ? true : false;
					if (this.question.dui == null) {
						this.question.dui = 0;
						this.question.cuo = 0;
					}
					this.question.isRight ? this.question.dui++ : this.question.cuo++;
					this.maskControll();
					
					this.$api.record({
								tid: question.id,
								zid: question.zid,
								text: that.text,
								type: that.question.isRight ? 1 : 2
					})
				} else {
					toast({
						title: '多选题至少选择两个答案',
						icon: 'none'
					});
				}
			},
			
			checkConfirm_wd() {
				
				const that = this;
				let question = this.question;
				if (this.question.userAnswer && this.question.userAnswer.length > 1) {
					this._optChange()
					this.question.disabled = true;
					this.question.finish = true;
					this.question.show = true;
					this.maskControll();
					
				} else {
					toast({
						title: '请填写答案',
						icon: 'none'
					});
				}
			},

			cancel() {
				this.mask = false;
			},
			confirm() {
				if (this.swiperConfig.audio) {
					this.audios.stop();
				}
				this.mask = false;
				this.nextPage();
			},
			// 切换收藏状态
			async collect() {
				const that = this;
				let question = this.question;
				let res = await that.$api.shoucang({
						tid: question.id,
						zid: question.zid,
						text: that.text,
						type: that.question.Collection ? 2 : 1
					}
				);
				
				if (res.code == 0) {
					this.question.Collection = !this.question.Collection;
					await that._optChange(1)
					uni.showToast({
						title: that.question.Collection ? '已收藏' : '已经取消收藏',
						icon: 'none'
					});
				}
			},
			// 点击头部返回按钮
			navBack() {
				let that = this;
				uni.showModal({
					title: '系统提示',
					content: '你确定要退出吗?',
					success(res) {
						if (res.confirm) {
						  uni.navigateBack();
						}
					}
				});
			},
		
			timeonChange(e){
				this.timeData = e
			},
			time_out(){
				this.submit_sj();
			},
			async sublimit(){
				const re= await this.$api.kstj_dt({
					anser:JSON.stringify(this.questions),
					type:this.text,
					sj:(this.ks_time-(this.timeData.hours*60*60*1000)-(this.timeData.minutes*60*1000)-(this.timeData.seconds*1000))/1000,
					ksid:this.id,
				})
				
				if(re.code==0){
					uni.removeStorageSync(this.storageKey);
					uni.$emit('updateValueInDataArr',{id:this.ksid,score:re.data.score})
					uni.navigateBack();
				}else{
					toast(re.msg);
				}
			},
			submit_sj(){
				const _this=this;
				let emptyBCount = _this.questions.filter(item => item.userAnswer == '').length;
				if(emptyBCount){
					uni.showModal({
						title: '提交问卷',
						content: `你有${emptyBCount}题未答,请答完再提交!`,
						success(res) {
						
						}
					}); 
				}else{
					_this.sublimit();
				}
				
			},
			ispic(url){
				return isImageUrlByExtension(url);
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import "@/tk.scss";
</style>